<template>
  <VuiModal v-if="downloadModal" v-model="downloadModal">
    <template #title>{{ translateTitle('Dams.ApplicationInterface.导出数据') }}</template>
    <div class="modal-body overflow-hidden w-[500px] min-h-[320px]">
      <div class="overflow-y-scroll scrollbar--light h-80">
        <el-form ref="subForm" class="demo-dynamic" label-width="100px" :model="subDownloadForm">
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.文件名')">
            <input v-model="subDownloadForm['#EXPORT_FILE_NAME#']" class="p-1 bg-gray-50" />
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.保存类型')">
            <input v-model="subDownloadForm['#EXPORT_FILE_TYPE#']" class="p-1 bg-gray-50" disabled />
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.选择数据')">
            <el-select v-model="subDownloadForm.type" :placeholder="translateTitle('Dams.ApplicationInterface.请选择')">
              <el-option v-for="item in downloadOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.选择字段')">
            <div class="overflow-y-auto" style="height: 200px">
              <div v-for="(item, index) in downloadColumns" :key="index">
                <el-checkbox v-model="item.checked">{{ item.label }}</el-checkbox>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-center p-3 border-t border-gray-100">
        <el-button type="success" @click="saveDownload">{{ translateTitle('Dams.ApplicationInterface.导出') }}</el-button>
      </div>
    </template>
  </VuiModal>
</template>
<script>
  import { download, getList } from '../api/home'
  import cloneDeep from 'lodash/cloneDeep'
  import { GFCD } from '@/utils/utils'
  import { export_json_to_excel } from '@ve/utils/exportExcel'
  import { translateTitle } from '@/utils/i18n'
  import list from './constant'
  export default {
    name: 'Download',
    props: {
      //是否显示弹框
      isModal: {
        type: Boolean,
        default: false,
      },
      //可选择的表头数据
      tableColumn: {
        type: Array,
        default: () => [],
      },
      //表格本页数据
      tablelist: {
        type: Array,
        default: () => [],
      },
      //表格选中数据
      checkboxlist: {
        type: Array,
        default: () => [],
      },
      //所属子系统
      subSystem: {
        type: String,
        default: 'dams',
      },
      //搜索表单
      searchForm: {
        type: Object,
        default: () => {},
      },
      //表格查询的methods
      searchTableMethods: {
        type: String,
        default: '',
      },
      //下载的methods
      downloadMethods: {
        type: String,
        default: '',
      },
    },
    emits: ['close'],
    data() {
      return {
        downloadColumns: [],
        downloadOptions: [
          { value: '1', label: translateTitle('Dams.ApplicationInterface.当前数据') },
          { value: '2', label: translateTitle('Dams.ApplicationInterface.选中数据') },
          { value: '3', label: translateTitle('Dams.ApplicationInterface.全量数据') },
        ],
        subDownloadForm: {
          type: '1',
          '#EXPORT_WHERE#': {},
          '#EXPORT_SQL_ID#': '',
          '#EXPORT_API_NAME#': '',
          '#QUERY_SORT#': '',
          '#EXPORT_FILE_NAME#': '',
          '#EXPORT_FILE_TYPE#': 'xlsx',
          '#EXPORT_SHEET_NAME#': '',
          '#EXPORT_COLUMN#': {},
        },
      }
    },
    computed: {
      downloadModal: {
        get() {
          return this.isModal
        },
        set(newValue) {
          this.$emit('close', newValue)
        },
      },
      pageTableList() {
        console.log(this.tablelist)
        return this.tablelist
      },
      columnsData() {
        let arr = this.tableColumn.filter((el) => el.label || el.title)
        console.log(arr)
        arr.forEach((row) => {
          row.checked = true
        })
        return arr
      },
    },
    watch: {
      columnsData(val) {
        this.downloadColumns = cloneDeep(val)
      },
    },
    mounted() {
      this.downloadColumns = cloneDeep(this.columnsData) || []
    },
    methods: {
      translateTitle,
      downloadPort(_data) {
        list.forEach((row) => {
          row['#EXPORT_WHERE#']['MESSAGE_GROUP_ID'] = _data.map((el) => el.MESSAGE_GROUP_ID).join(',')
          row['#EXPORT_FILE_NAME#'] = this.subDownloadForm['#EXPORT_FILE_NAME#']
            ? this.subDownloadForm['#EXPORT_FILE_NAME#']
            : translateTitle('Dams.ApplicationInterface.导出文件') + '_' + new Date().getTime()
        })
        console.log(list)
        let url
        if (this.subSystem == 'wms') {
          url = GFCD('dams', 'domain') + '/wms/wms-web'
        } else {
          url = GFCD(this.subSystem, 'domain') + GFCD(this.subSystem, 'baseUrl')
        }
        download(url, {
          data: JSON.stringify(list),
          method: this.downloadMethods,
        }).then((res) => {
          console.log(res)
          let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
          let reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = (e) => {
            let a = document.createElement('a')
            a.download = list[0]['#EXPORT_FILE_NAME#'] + '.xlsx'
            a.href = e.target.result
            a.click()
            this.downloadModal = false
            this.$emit('close', false)
          }
        })
      },
      setFirstLineData(filterVal, pageData) {
        let list = cloneDeep(pageData)
        let valObj = {}
        filterVal.forEach((row) => {
          valObj[row] = row
        })
        list.unshift(valObj)
        return list
      },
      saveDownload() {
        console.log(this.downloadMethods)
        let methodApi = [
          'apim.message.config.export',
          'apim.message.config.value.export',
          'apim.message.field.mapping.export',
          'apim.message.field.xml.export',
          'apim.message.config.value.export',
          'apim.message.structure.export',
          'apim.message.id.export',
          'apim.rule.message.export',
          'apim.send.std.table.export',
          'apim.std.rule.export',
          'apim.std.table.export',
          'dams.language.pack.export',
        ]
        // if (this.subSystem) return
        //勾选了的表头
        let columns = this.downloadColumns.filter((el) => el.checked)
        //表格本页数据
        let pageData = this.pageTableList
        //表格选中数据
        let checkboxData = this.checkboxlist
        const multiHeader = columns.map((el) => el.label || el.title) //表头显示
        const filterVal = columns.map((el) => el.porp || el.name) //表头所对应后台返回的字段
        let columnObj = {}
        columns.forEach((row) => {
          columnObj[row.porp] = row.label
        })
        let data
        if (this.subDownloadForm.type == '3') {
          if (this.downloadMethods == 'apim.collection.cust.org.export') {
            let url
            if (this.subSystem == 'wms') {
              url = GFCD('dams', 'domain') + '/wms/wms-web'
            } else {
              url = GFCD(this.subSystem, 'domain') + GFCD(this.subSystem, 'baseUrl')
            }
            getList(url, {
              data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }),
              method: 'ApimCustOrgQuery',
            }).then((res) => {
              console.log(res.data['ApimCustOrgQuery'].data)
              this.downloadPort(res.data['ApimCustOrgQuery'].data)
            })
          } else {
            //调用接口下载
            let p = cloneDeep(this.subDownloadForm)
            delete p.type
            let subP, url
            if (Array.isArray(this.searchForm)) {
              subP = cloneDeep(this.searchForm[0])
            } else {
              subP = cloneDeep(this.searchForm)
            }
            console.log(subP)
            if (subP.CREATE_TIME) delete subP.CREATE_TIME
            p['#EXPORT_WHERE#'] = subP
            if (methodApi.indexOf(this.downloadMethods) > -1) {
              p['#WRITE_FIELD_ROWS#'] = 'Y'
            }
            p['#EXPORT_SQL_ID#'] = this.searchTableMethods
            p['#EXPORT_API_NAME#'] = this.searchTableMethods
            if (this.downloadMethods == 'apim.message.config.export') {
              columnObj['RETURN_CONDITION'] = '回调前置条件'
            }
            p['#EXPORT_COLUMN#'] = columnObj
            // p['#EXPORT_SHEET_NAME#'] = this.name
            p['#EXPORT_FILE_NAME#'] = this.subDownloadForm['#EXPORT_FILE_NAME#']
              ? this.subDownloadForm['#EXPORT_FILE_NAME#']
              : translateTitle('Dams.ApplicationInterface.导出文件') + '_' + new Date().getTime()
            if (this.subSystem == 'wms') {
              url = GFCD('dams', 'domain') + '/wms/wms-web'
            } else {
              url = GFCD(this.subSystem, 'domain') + GFCD(this.subSystem, 'baseUrl')
            }
            download(url, {
              data: JSON.stringify(p),
              method: this.downloadMethods,
            }).then((res) => {
              console.log(res)
              let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
              let reader = new FileReader()
              reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
              reader.onload = (e) => {
                let a = document.createElement('a')
                a.download = p['#EXPORT_FILE_NAME#'] + '.xlsx'
                a.href = e.target.result
                a.click()
                this.downloadModal = false
                this.$emit('close', false)
              }
            })
          }
        } else {
          //前端下载
          if (this.downloadMethods == 'apim.collection.cust.org.export') {
            if (this.subDownloadForm.type == '1') {
              this.downloadPort(pageData)
            } else {
              this.downloadPort(checkboxData)
            }
          } else {
            // if (methodApi.indexOf(this.downloadMethods) > -1) {
            //   p['#WRITE_FIELD_ROWS#'] = 'Y'
            // }
            if (this.downloadMethods == 'apim.message.config.export') {
              // columnObj['RETURN_CONDITION'] = '回调前置条件'
              filterVal.push('RETURN_CONDITION')
              multiHeader.push('回调前置条件')
            }
            if (this.subDownloadForm.type == '1') {
              if (pageData.length == 0) return this.$baseMessage(translateTitle('Dams.ApplicationInterface.暂无数据'), 'error')
              if (methodApi.indexOf(this.downloadMethods) > -1) {
                data = this.formatJson(filterVal, this.setFirstLineData(filterVal, pageData))
              } else {
                data = this.formatJson(filterVal, pageData) //本页数据格式化
              }
            } else {
              if (checkboxData.length == 0) return this.$baseMessage(translateTitle('Dams.ApplicationInterface.请选择数据'), 'error')
              if (methodApi.indexOf(this.downloadMethods) > -1) {
                data = this.formatJson(filterVal, this.setFirstLineData(filterVal, checkboxData))
              } else {
                data = this.formatJson(filterVal, checkboxData) //本页数据格式化
              }
            }
            export_json_to_excel({
              multiHeader, //这里是第一行的表头
              data, //数据
              filename: this.subDownloadForm['#EXPORT_FILE_NAME#']
                ? this.subDownloadForm['#EXPORT_FILE_NAME#']
                : '导出文件' + '_' + new Date().getTime(),
              bookType: 'xlsx',
            })
            this.downloadModal = false
            this.$emit('close', false)
          }
        }
      },
      //json格式化
      formatJson(filterVal, jsonData) {
        jsonData.map((v) => filterVal.map((j) => (v[j] ? v[j] : '')))
        return jsonData.map((v) => filterVal.map((j) => (v[j] ? v[j] : '')))
      },
    },
  }
</script>
